import { constantRoutes } from '@/router';
import { getRouters } from '@/api/menu';
import { getInfo } from '@/api/login';
import Layout from '@/layout/index';

const permission = {
    state: {
        routes: [],
        addRoutes: []
    },
    mutations: {
        SET_ROUTES: (state, routes) => {
            state.addRoutes = routes;
            state.routes = constantRoutes.concat(routes);
        }
    },
    actions: {
        // 生成路由
        GenerateRoutes({ commit }) {
            return new Promise(resolve => {
                // 向后端请求路由数据
                getRouters().then(res => {
                    getInfo().then(ress => {
                        // this.store.state.user.toPath = res.ApplyStatus;
                        localStorage.userId = ress.ApplyStatus;
                        let accessedRoutes = filterAsyncRouter(res.data, ress.ApplyStatus,ress.roles[0]);
                        // console.log('--------------------');
                        // console.log(ress);
                        // console.log(accessedRoutes);
                        // console.log('--------------------');
                        accessedRoutes.forEach(element => {
                            if (element.path == '/money' && ress.settype != '1') {
                                element.children.splice(0, 1);
                            }
                            if (element.path == "/company" && ress.ApplyStatus == '2') {
                                element.hidden = true;
                            }
                        });

                        let list = [];
                        list = accessedRoutes;
                        list.push({
                            path: '*',
                            redirect: '/404',
                            hidden: true
                        });
                        commit('SET_ROUTES', list);
                        resolve(list);
                    });
                });
            });
        }
    }
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, appltStatus, reole) {
    return asyncRouterMap.filter(route => {
        if (appltStatus == 0 || appltStatus == 1 || appltStatus == 3) {
            route.hidden = true;
        }
        if (reole != "common") {
            route.hidden = false;
        }
        if (route.component) {
            // Layout组件特殊处理
            if (route.component === 'Layout') {
                route.component = Layout;
            } else {
                route.component = loadView(route.component);
            }
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children);
        }
        return true;
    });
}

export const loadView = view => {
    // 路由懒加载
    return resolve => require([`@/views/${view}`], resolve);
};

export default permission;
